<? require_once "setup.php" ?>

<?
class Room {
  public $type = 0;
  public $price = 0;
  public $available = 0;
}

function readInt($socket) {
  $n = socket_read($socket, 4);
  $unpacked = unpack("N", $n);
  return $unpacked[1];
}

function writeInt($socket, $value) {
  socket_write($socket, pack("N", $value), 4);
}

function readString($socket) {
  $n = readInt($socket);
  return socket_read($socket, $n);
}

function writeString($socket, $value) {
  $len = strlen($value);
  writeInt($socket, $len);
  socket_write($socket, $value, $len);
}

class Hotel {

  const ROOMS_REQUEST = 1;
  const BOOK_REQUEST = 2;
  const GUESTS_REQUEST = 3;
  
  static function create_socket_to_gateway() {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $result = socket_connect($socket, ConferenceSetup::HOTEL_GATEWAY_ADDR, ConferenceSetup::HOTEL_GATEWAY_PORT);
    return $socket;  
  }

  static function getRooms() {
    $socket = Hotel::create_socket_to_gateway();
    writeInt($socket, Hotel::ROOMS_REQUEST);
    $n = readInt($socket);
    for ($i = 0; $i < $n; $i++) {
      $result[$i]["id"] = readInt($socket);
      $result[$i]["free"] = readInt($socket);
      $result[$i]["price"] = readInt($socket);
    }
    socket_close($socket);  
    return $result;
  }

  static function getParticipants() {
    $socket = Hotel::create_socket_to_gateway();
    writeInt($socket, Hotel::GUESTS_REQUEST);
    $n = readInt($socket, Hotel::ROOMS_REQUEST);
    for ($i = 1; $i <= $n; $i++) {
      $result[$i] = readString($socket);
    }
    socket_close($socket);
    return $result;
  }

  static function bookRoom($type, $participantName) {
    $socket = Hotel::create_socket_to_gateway();
    writeInt($socket, Hotel::BOOK_REQUEST);
    writeInt($socket, $type);
    writeString($socket, $participantName);
    $result = readInt($socket);
    if ($result <> 0) {
      $result = readString($socket);
    }
    socket_close($socket);
    return $result == 0 ? nil : $result;
  }
}

?>
